package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.li.work.mapper.SysUserRoleMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.PlatformCCourseVO;
import com.ruoyi.teaching.domain.vo.PlatformFForumVO;
import com.ruoyi.teaching.mapper.PlatformFForumMapper;
import com.ruoyi.teaching.mapper.PlatformFLikeMapper;
import com.ruoyi.teaching.mapper.PlatformFZoneMapper;
import com.ruoyi.teaching.service.PlatformFForumService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-10-14
 */
@Service
public class PlatformFForumServiceImpl extends ServiceImpl<PlatformFForumMapper, PlatformFForum> implements PlatformFForumService {

    @Autowired
    private PlatformFForumMapper platformFForumMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private PlatformFLikeMapper likeMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private PlatformFZoneMapper platformFZoneMapper;

    /**
     * @param pageNum  第几页
     * @param pageSize 几条
     * @param zoneId   分类id
     * @param message  内容搜索
     * @param type     排序 0热门1最新
     * @return
     */
    @Override
    public AjaxResult forumList(Integer pageNum, Integer pageSize, Integer zoneId, String message, Integer type) {
        Page<PlatformFForum> platformFForumPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFForum> platformFForumQueryWrapper = new QueryWrapper<>();
        platformFForumQueryWrapper.isNull("top_id");
        if (null != zoneId && zoneId != 0) {
            platformFForumQueryWrapper.eq("zone_id", zoneId);
        }
        if (null != message && !message.equals("")) {
            platformFForumQueryWrapper.and(wrapper ->
                    wrapper.like("message", message)
                            .or()
                            .like("title", message));
        }

        if (null == type || 1 == type) {
            platformFForumQueryWrapper.orderByDesc("create_time");
        } else if (0 == type) {
            platformFForumQueryWrapper.orderByDesc("like_num").orderByDesc("create_time");
        }
        List<Long> delZoneId = getDelZoneId();
        if (!delZoneId.isEmpty()) {
            platformFForumQueryWrapper.notIn("zone_id", delZoneId);
        }
        Page<PlatformFForum> platformFForumPage1 = platformFForumMapper.selectPage(platformFForumPage, platformFForumQueryWrapper);
        Page<PlatformFForumVO> platformFForumVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformFForumPage1, platformFForumVOPage);
        List<PlatformFForumVO> platformFForumVOS = new ArrayList<>();
        for (PlatformFForum record : platformFForumPage1.getRecords()) {
            PlatformFForumVO platformFForumVO = new PlatformFForumVO();
            BeanUtils.copyProperties(record, platformFForumVO);
            SysUser user = userMapper.selectUserById(Long.valueOf(record.getCreateId()));
            if (null != user) {
                if (null != user.getAvatar()) {
                    platformFForumVO.setCreateUrl(user.getAvatar());
                }
                if (null != user.getNickName()) {
                    platformFForumVO.setCreateBy(user.getNickName());
                }
            }
            String imageUrl = record.getImageUrl();
            if (null != imageUrl && !imageUrl.equals("")) {
                String[] imageUrls = imageUrl.split(",");
                platformFForumVO.setImageUrl(imageUrls);
            }
            // 添加本人是否点赞信息
            Long userId = getCurrentUserId();
            // 设置点赞状态
            platformFForumVO.setIsLike(getUserLikeStatus(record.getId(), userId));

            // 查找当前帖子下的评论
            List<PlatformFForumVO> topLevelComments = getComment(Math.toIntExact(platformFForumVO.getId()));
            Page<PlatformFForumVO> page = toPage(topLevelComments, 1, 10, platformFForumVO);
            platformFForumVO.setChildrenPage(page);

            platformFForumVOS.add(platformFForumVO);
        }
        platformFForumVOPage.setRecords(platformFForumVOS);
        if (null != zoneId && zoneId != 0) {
            platformFForumVOPage.setCountId(platformFZoneMapper.selectById(zoneId).getZoneName());
        }
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformFForumVOPage);
    }

    private List<Long> getDelZoneId() {
        QueryWrapper<PlatformFZone> platformFZoneQueryWrapper = new QueryWrapper<>();
        platformFZoneQueryWrapper.eq("del_flag", 1);
        List<PlatformFZone> platformFZones = platformFZoneMapper.selectList(platformFZoneQueryWrapper);
        List<Long> delZoneIds = new ArrayList<>();
        for (PlatformFZone zone : platformFZones) {
            delZoneIds.add(zone.getId());
        }
        return delZoneIds;
    }

    @Override
    public AjaxResult forumCommentList(Integer forumId, Integer pageNum, Integer pageSize) {

        List<PlatformFForumVO> topLevelComments = getComment(forumId);

        // 返回封装的顶级评论列表
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", toPage(topLevelComments, pageNum, pageSize, null));
    }

    private List<PlatformFForumVO> getComment(Integer forumId) {
        // 构建查询条件，查询指定 forumId 的评论
        QueryWrapper<PlatformFForum> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("top_id", forumId);

        // 获取所有符合条件的评论列表
        List<PlatformFForum> forums = platformFForumMapper.selectList(queryWrapper);
        List<PlatformFForumVO> forumVOList = new ArrayList<>();

        // 遍历评论，将 PlatformFForum 转换为 PlatformFForumVO，同时获取用户信息
        for (PlatformFForum forum : forums) {
            PlatformFForumVO forumVO = new PlatformFForumVO();
            BeanUtils.copyProperties(forum, forumVO);

            // 获取回复用户的昵称并设置到 VO 中
            SysUser replyUser = userMapper.selectUserById(forumVO.getReplyUserId());
            forumVO.setReplyUserName(replyUser != null ? replyUser.getNickName() : "用户不存在");

            SysUser user = userMapper.selectUserById(Long.valueOf(forumVO.getCreateId()));
            // 设置用户头像
            if (null != user) {
                if (null != user.getAvatar()) {
                    forumVO.setCreateUrl(user.getAvatar());
                }
            }

            // 添加本人是否点赞信息
            Long userId = getCurrentUserId();
            // 设置点赞状态
            forumVO.setIsLike(getUserLikeStatus(forum.getId(), userId));

            forumVOList.add(forumVO);
        }

        // 过滤出顶级评论（即没有 topCommentId 的评论）
        List<PlatformFForumVO> topLevelComments = forumVOList.stream()
                .filter(forumVO -> forumVO.getTopCommentId() == null)
                .collect(Collectors.toList());

        // 为每个顶级评论找到其子评论，并设置到 VO 的 children 属性中
        for (PlatformFForumVO topComment : topLevelComments) {
            List<PlatformFForumVO> childComments = forumVOList.stream()
                    .filter(forumVO -> forumVO.getTopCommentId() != null && forumVO.getTopCommentId().equals(topComment.getId()))
                    .collect(Collectors.toList());
            topComment.setChildren(childComments);
        }

        return topLevelComments;
    }

    @Override
    public AjaxResult ownCommentList(Integer pageNum, Integer pageSize, Integer type) {
        // 分页参数构造，设置分页查询的页码和每页大小
        Page<PlatformFForum> forumPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFForum> queryWrapper = new QueryWrapper<>();

        // 获取当前登录用户的 ID
        Long userId = SecurityUtils.getUserId();

        // 查询所有非帖子，type 为0看我的评论，1为我收到的评论（此处代码为非0都是我收到的评论，默认是我的评论）
        if (null == type) {
            type = 0;
        } else if (type > 1) {
            type = 0;
        }
        queryWrapper.eq(type == 0 ? "create_id" : "reply_user_id", userId).isNotNull("top_id").orderByDesc("create_time");

        List<Long> delZoneId = getDelZoneId();
        if (!delZoneId.isEmpty()) {
            queryWrapper.notIn("zone_id", delZoneId);
        }

        // 分页查询评论
        Page<PlatformFForum> resultPage = platformFForumMapper.selectPage(forumPage, queryWrapper);

        // 初始化 VO 的分页对象，方便数据封装
        Page<PlatformFForumVO> forumVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(resultPage, forumVOPage); // 复制分页信息到 VO 的分页对象

        // 用于存储 PlatformFForumVO 对象
        List<PlatformFForumVO> forumVOList = new ArrayList<>();

        // 遍历查询结果，将 PlatformFForum 转换为 PlatformFForumVO
        for (PlatformFForum record : resultPage.getRecords()) {
            PlatformFForumVO forumVO = new PlatformFForumVO();
            BeanUtils.copyProperties(record, forumVO);

            // 获取回复用户的昵称并设置到 VO 中
            Long replyUserId = type == 0 ? forumVO.getReplyUserId() : Long.valueOf(forumVO.getCreateId());
            String replyUserName = "";
            if (userId == replyUserId) {
                replyUserName = "我";
            } else {
                SysUser user = userMapper.selectUserById(replyUserId);
                replyUserName = user != null ? user.getNickName() : "用户不存在";
                forumVO.setReplyUserName(replyUserName);
            }

            // 根据评论是否为顶级评论设置标题或评论内容
            if (forumVO.getTopCommentId() == null) {
                // 如果没有顶级评论 ID，说明该评论是针对帖子，获取帖子标题
                PlatformFForum forum = platformFForumMapper.selectById(forumVO.getTopId());
                String parentMessage = forum != null ? forum.getMessage() : "帖子已被删除";
                forumVO.setCommentTitle(type == 0 ? replyUserName + "：" + parentMessage : "我：" + parentMessage);
            } else {
                // 否则获取该评论的父评论内容
                PlatformFForum forum = platformFForumMapper.selectById(forumVO.getCommentId());
                String parentMessage = forum != null ? forum.getMessage() : "评论已被删除";
                forumVO.setCommentTitle(type == 0 ? replyUserName + "：" + parentMessage : "我：" + parentMessage);
            }
            if (type != 0) {
                forumVO.setMessage(replyUserName + "：" + forumVO.getMessage());
            }

            // 添加帖子信息
            PlatformFForum platformFForum1 = platformFForumMapper.selectById(forumVO.getTopId());
            if (null != platformFForum1) {
                PlatformFForumVO platformFForumVO = new PlatformFForumVO();
                BeanUtils.copyProperties(platformFForum1, platformFForumVO);
                SysUser user = userMapper.selectUserById(Long.valueOf(platformFForum1.getCreateId()));
                if (null != user) {
                    if (null != user.getAvatar()) {
                        platformFForumVO.setCreateUrl(user.getAvatar());
                    }
                }
                String imageUrl = platformFForum1.getImageUrl();
                if (null != imageUrl && !imageUrl.equals("")) {
                    String[] imageUrls = imageUrl.split(",");
                    platformFForumVO.setImageUrl(imageUrls);
                }
                // 添加本人是否点赞信息
                Long userId1 = getCurrentUserId();
                // 设置点赞状态
                platformFForumVO.setIsLike(getUserLikeStatus(platformFForum1.getId(), userId1));

                // 查找当前帖子下的评论
                List<PlatformFForumVO> topLevelComments = getComment(Math.toIntExact(platformFForumVO.getId()));
                Page<PlatformFForumVO> page = toPage(topLevelComments, 1, 10, platformFForumVO);
                platformFForumVO.setChildrenPage(page);
                forumVO.setPlatformFForumVO(platformFForumVO);
            }
            // 添加转换后的 VO 对象到列表
            forumVOList.add(forumVO);
        }

        // 将封装好的 VO 列表设置到分页对象中
        forumVOPage.setRecords(forumVOList);

        // 返回 Ajax 结果，包含分页后的评论数据
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", forumVOPage);
    }

    /**
     * @param pageNum  第几页
     * @param pageSize 几条
     * @param zoneId   分类id
     * @param time     时间条件 0是全部1是一天内2是一周内3是一个月内4是三个月内
     * @return
     */
    @Override
    public AjaxResult myForumList(Integer pageNum, Integer pageSize, Integer zoneId, String time) {
        Page<PlatformFForum> platformFForumPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFForum> queryWrapper = new QueryWrapper<>();

        // 只查询顶级帖子
        queryWrapper.isNull("top_id");

        // 按分区 ID 进行筛选
        if (zoneId != null && zoneId != 0) {
            queryWrapper.eq("zone_id", zoneId);
        }

        // 根据 time 值计算时间范围并进行筛选
        LocalDateTime now = LocalDateTime.now();
        if (time != null) {
            switch (time) {
                case "1":
                    // 一天内
                    queryWrapper.ge("create_time", now.minusDays(1));
                    break;
                case "2":
                    // 一周内
                    queryWrapper.ge("create_time", now.minusWeeks(1));
                    break;
                case "3":
                    // 一个月内
                    queryWrapper.ge("create_time", now.minusMonths(1));
                    break;
                case "4":
                    // 三个月内
                    queryWrapper.ge("create_time", now.minusMonths(3));
                    break;
                case "5":
                    // 六个月内
                    queryWrapper.ge("create_time", now.minusMonths(6));
                    break;
                case "6":
                    // 一年内
                    queryWrapper.ge("create_time", now.minusYears(1));
                    break;
                case "7":
                    // 两年内
                    queryWrapper.ge("create_time", now.minusYears(2));
                    break;
                default:
                    // 全部数据，不做时间过滤
                    break;
            }
        }

        Long userId = SecurityUtils.getUserId();
        queryWrapper.eq("create_id", userId);
        queryWrapper.orderByDesc("create_time");

        List<Long> delZoneId = getDelZoneId();
        if (!delZoneId.isEmpty()) {
            queryWrapper.notIn("zone_id", delZoneId);
        }

        // 执行分页查询
        Page<PlatformFForum> forumPage = platformFForumMapper.selectPage(platformFForumPage, queryWrapper);

        // 初始化 VO 分页对象
        Page<PlatformFForumVO> platformFForumVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(forumPage, platformFForumVOPage);

        List<PlatformFForumVO> platformFForumVOS = new ArrayList<>();

        // 转换 PlatformFForum 为 PlatformFForumVO，并处理图片 URL
        for (PlatformFForum record : forumPage.getRecords()) {
            PlatformFForumVO platformFForumVO = new PlatformFForumVO();
            BeanUtils.copyProperties(record, platformFForumVO);

            // 处理图片链接字符串，将其拆分成数组
            String imageUrl = record.getImageUrl();
            if (imageUrl != null && !imageUrl.isEmpty()) {
                String[] imageUrls = imageUrl.split(",");
                platformFForumVO.setImageUrl(imageUrls);
            }

            // 添加创建者头像
            SysUser user = userMapper.selectUserById(Long.valueOf(record.getCreateId()));
            if (null != user) {
                if (null != user.getAvatar()) {
                    platformFForumVO.setCreateUrl(user.getAvatar());
                }
            }

            // 设置点赞状态
            platformFForumVO.setIsLike(getUserLikeStatus(record.getId(), userId));

            // 添加分区名称
            PlatformFZone platformFZone = platformFZoneMapper.selectById(platformFForumVO.getZoneId());
            platformFForumVO.setZoneName(platformFZone.getZoneName());

            // 查找当前帖子下的评论
            List<PlatformFForumVO> topLevelComments = getComment(Math.toIntExact(platformFForumVO.getId()));
            Page<PlatformFForumVO> page = PlatformFForumServiceImpl.toPage(topLevelComments, 1, 10, platformFForumVO);
            platformFForumVO.setChildrenPage(page);

            platformFForumVOS.add(platformFForumVO);
        }

        platformFForumVOPage.setRecords(platformFForumVOS);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformFForumVOPage);
    }


    @Override
    public AjaxResult addForumComment(PlatformFForumVO platformFForumVO) {
        PlatformFForum platformFForum = new PlatformFForum();
        BeanUtils.copyProperties(platformFForumVO, platformFForum);
        String[] imageUrl = platformFForumVO.getImageUrl();
        if (imageUrl != null && imageUrl.length > 0) {
            // 将数组转为以逗号分隔的字符串
            String imageUrlStr = String.join(",", imageUrl);
            platformFForum.setImageUrl(imageUrlStr);
        }
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(userMapper);
        platformFForum.setCreateBy(update.getName());
        platformFForum.setCreateTime(DateUtils.getNowDate());
        platformFForum.setCreateId(update.getId());
        int i = platformFForumMapper.insert(platformFForum);
        if (i > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "发布成功");
        } else {
            return new AjaxResult(HttpStatus.ERROR, "发布失败");
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteForumComment(Long[] ids) {
        Long userId = SecurityUtils.getUserId();
        int roleId = Math.toIntExact(sysUserRoleMapper.selectRoleIdbyUserId(userId)[0]);
        boolean roleSystemAdmin = (roleId == 1 || roleId == 6); // 超级管理员

        if (roleSystemAdmin) {
            int deletedCount = 0;
            for (Long id : ids) {
                PlatformFForum platformFForum = platformFForumMapper.selectById(id);
                int rowsDeleted = platformFForumMapper.deleteById(id);
                if (rowsDeleted > 0) {
                    deletedCount++;
                    if(platformFForum.getTopCommentId() == null && platformFForum.getTopId() != null){
                        platformFForumMapper.delete(new QueryWrapper<PlatformFForum>().eq("top_comment_id", id));
                    }
                }
            }
            if (deletedCount == ids.length) {
                return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "删除失败");
            }
        } else {
            int successfulDeletions = 0;
            for (Long id : ids) {
                PlatformFForum platformFForum = platformFForumMapper.selectById(id);
                if (platformFForum != null) {
                    if (platformFForum.getTopId() != null) {
                        PlatformFForum platformFForum1 = platformFForumMapper.selectById(platformFForum.getTopId());
                        if (platformFForum1 != null) {
                            if ((userId.intValue()) == platformFForum1.getCreateId()) {
                                int rowsDeleted = platformFForumMapper.deleteById(id);
                                if (rowsDeleted > 0) {
                                    successfulDeletions++;
                                    if(platformFForum.getTopCommentId() == null && platformFForum.getTopId() != null){
                                        platformFForumMapper.delete(new QueryWrapper<PlatformFForum>().eq("top_comment_id", id));
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (successfulDeletions == ids.length) {
                return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
            } else {
                throw new RuntimeException("无法删除他人数据");
            }
        }
    }

    /**
     * @param forumId 当前点击的id
     * @param type    从哪里点的 0帖子1评论2点赞
     * @return
     */
    @Override
    public AjaxResult detail(Integer forumId, Integer type, Integer pageNum, Integer pageSize) {
        if (type == null) {
            return new AjaxResult(HttpStatus.ERROR, "非法获取");
        }

        if (type == 0 || type == 2) {
            PlatformFForum platformFForum = platformFForumMapper.selectById(forumId);
            if (platformFForum == null) {
                return new AjaxResult(HttpStatus.ERROR, "未找到相关论坛信息");
            }
            PlatformFForum forum = type == 0 ? platformFForum
                    : platformFForumMapper.selectById(platformFForum.getTopId());
            return getForumDetail(forum, pageNum, pageSize);
        } else if (type == 1) {
            PlatformFLike platformFLike = likeMapper.selectById(forumId);
            if (platformFLike == null) {
                // 防止 platformFLike 为空的情况
                return new AjaxResult(HttpStatus.ERROR, "未找到相关论坛信息");
            }

            Long objectId = platformFLike.getObjectId();

            PlatformFForum forum = null;
            if (platformFLike.getLikeType() == 0) {
                forum = platformFForumMapper.selectById(objectId);
            } else {
                PlatformFForum tempForum = platformFForumMapper.selectById(objectId);
                if (tempForum != null) {
                    forum = platformFForumMapper.selectById(tempForum.getTopId());
                }
            }

            return getForumDetail(forum, pageNum, pageSize);
        }

        return new AjaxResult(HttpStatus.ERROR, "非法获取");
    }

    /**
     * 获取论坛详情，包括论坛信息、点赞信息、评论信息等。
     *
     * @param forum 论坛实体对象
     * @return 包含论坛详细信息的 AjaxResult 对象
     */
    private AjaxResult getForumDetail(PlatformFForum forum, Integer pageNum, Integer pageSize) {
        // 论坛为空时返回错误信息
        if (forum == null) {
            return new AjaxResult(HttpStatus.ERROR, "未找到相关论坛信息");
        }

        // 创建 VO 对象并拷贝属性
        PlatformFForumVO platformFForumVO = new PlatformFForumVO();
        BeanUtils.copyProperties(forum, platformFForumVO);

        // 获取创建人信息
        SysUser user = userMapper.selectUserById(Long.valueOf(forum.getCreateId()));
        // 设置创建人头像
        Optional.ofNullable(user)
                .map(SysUser::getAvatar)
                .ifPresent(platformFForumVO::setCreateUrl);

        // 将图片 URL 解析为数组
        Optional.ofNullable(forum.getImageUrl())
                .filter(imageUrl -> !imageUrl.isEmpty())
                .ifPresent(imageUrl -> platformFForumVO.setImageUrl(imageUrl.split(",")));

        // 添加本人是否点赞信息
        Long userId = getCurrentUserId();  // 获取当前用户 ID，如果未登录则为 null
        platformFForumVO.setIsLike(getUserLikeStatus(forum.getId(), userId));

        // 添加分区名称
        PlatformFZone platformFZone = platformFZoneMapper.selectById(platformFForumVO.getZoneId());
        platformFForumVO.setZoneName(platformFZone.getZoneName());

        // 查找当前帖子下的评论
        List<PlatformFForumVO> topLevelComments = getComment(Math.toIntExact(platformFForumVO.getId()));
        Page<PlatformFForumVO> page = toPage(topLevelComments, pageNum, pageSize, platformFForumVO);
        platformFForumVO.setChildrenPage(page);

        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", platformFForumVO);
    }

    /**
     * 获取当前登录用户的 ID，如果用户未登录则返回 null。
     *
     * @return 当前用户 ID 或 null
     */
    static Long getCurrentUserId() {
        try {
            return SecurityUtils.getUserId();  // 获取当前用户 ID
        } catch (ServiceException e) {
            return null;  // 如果用户未登录则返回 null
        }
    }

    /**
     * 获取用户对特定对象的点赞状态。
     *
     * @param objectId 点赞对象的 ID
     * @param userId   用户 ID
     * @return 如果用户已点赞则返回 1，否则返回 0
     */
    private int getUserLikeStatus(Long objectId, Long userId) {
        if (userId == null) {
            return 0;  // 如果用户未登录，返回未点赞状态
        }

        // 构建查询条件
        QueryWrapper<PlatformFLike> likeQueryWrapper = new QueryWrapper<>();
        likeQueryWrapper.eq("object_id", objectId);
        likeQueryWrapper.eq("create_id", userId);

        // 判断是否有点赞记录
        return likeMapper.selectCount(likeQueryWrapper) > 0 ? 1 : 0;
    }

    static Page<PlatformFForumVO> toPage(List<PlatformFForumVO> courses, Integer pageNum, Integer pageSize, PlatformFForumVO topPlatformFForumVO) {
        // 确定分页参数
        int total = courses.size();
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        int start = Math.min((pageNum - 1) * pageSize, total);
        int end = Math.min(start + pageSize, total);

        // 获取当前页的数据
        List<PlatformFForumVO> paginatedList = courses.subList(start, end);

        // 算出父子所有数据条数
        int i = 0;
        for (PlatformFForumVO platformFForumVO : courses) {
            i += platformFForumVO.getChildren().size();
        }
        i += total;

        // 设置分页信息
        Page<PlatformFForumVO> page = new Page<>(pageNum, pageSize);
        page.setRecords(paginatedList);
        page.setTotal(total);
        page.setMaxLimit((long) i);
        if (null != topPlatformFForumVO) {
            topPlatformFForumVO.setReplyUserId((long) i);
        }
        return page;
    }

    @Override
    public AjaxResult backForumList(Integer pageNum, Integer pageSize, String title, String createBy, Integer zoneId) {
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        Page<PlatformFForum> platformFForumPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformFForum> queryWrapper = new QueryWrapper<>();
        if (null != title && !"".equals(title)) {
            queryWrapper.like("title", title);
        }
        if (null != createBy && !"".equals(createBy)) {
            queryWrapper.like("create_by", createBy);
        }
        if (null != zoneId) {
            queryWrapper.eq("zone_id", zoneId);
        }
        queryWrapper.orderByDesc("create_time");
        queryWrapper.isNull("top_id");
        List<Long> delZoneId = getDelZoneId();
        if (!delZoneId.isEmpty()) {
            queryWrapper.notIn("zone_id", delZoneId);
        }
        IPage<PlatformFForum> page = platformFForumMapper.selectPage(platformFForumPage, queryWrapper);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", page);
    }
}
